package com.zy.DingDongServer.controller;

import com.alibaba.fastjson.JSON;
import com.zy.DingDongServer.entity.Friend;
import com.zy.DingDongServer.entity.Message;
import com.zy.DingDongServer.entity.User;
import com.zy.DingDongServer.service.FriendService;
import com.zy.DingDongServer.service.MessageService;
import com.zy.DingDongServer.service.UserService;
import com.zy.DingDongServer.util.DResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class UserController {

    @Value("${file.isLinux}")
    String isLinux;
    @Value("${file.imagesPath}")
    String imageRootPath;

    public final static String USER_HEADING_ROOT_PATH = "UserHeading/";
    public final static String MESSAGE_PICTURE_ROOT_PATH = "MessagePicture/";

    @Autowired
    UserService userService;
    @Autowired
    FriendService friendService;
    @Autowired
    MessageService messageService;

    /*
     * 测试接口测试工具postman的连接
     **/
    @PostMapping(value = "/user/test")
    public DResultMsg testPostman(@RequestParam(name = "username")String username){
        if (username.equals("zhangsan")){
            return new DResultMsg(DResultMsg.SUCCESS);
        } else {
          return new DResultMsg(DResultMsg.ERROR,"登录失败");
        }
    }

    @GetMapping(value = "/user/{username}/sendCheckCode")
    public DResultMsg sendCheckCode(@PathVariable("username") String username){
        if (userService.sendCheckCode(username)){
            return new DResultMsg(DResultMsg.SUCCESS);
        }else {
            return new DResultMsg(DResultMsg.ERROR,"阿里短信服务：3次/分钟；5次/小时；10次/天");
        }
    }
    @PostMapping(value = "/user/register")
    public DResultMsg register(@RequestParam(name = "jsonStr") String jsonStr){
        Map params = JSON.parseObject(jsonStr);
        User newUser = new User();
        //设置默认昵称和图片
        newUser.setName("默认昵称");
        newUser.setImagePath("http://photocdn.sohu.com/20110508/Img307009056.jpg");
        newUser.setUsername((String) params.get("newUsername"));
        newUser.setPassword((String) params.get("newPassword"));
        String message = userService.register(newUser);
        if (message.equals("success")){
            return new DResultMsg(DResultMsg.SUCCESS);
        }else {
            return new DResultMsg(DResultMsg.ERROR,message);
        }
    }
    @PostMapping(value = "/user/forgetPW")
    public DResultMsg forgetPW(@RequestParam(name = "jsonStr") String jsonStr){
        Map params = JSON.parseObject(jsonStr);
        User user = new User();
        user.setUsername((String) params.get("username"));
        user.setPassword((String) params.get("newPassword"));
        //String checkCode = (String) params.get("checkCode");
        //String message = userService.forgetPW(user,checkCode);
        String message = userService.forgetPW(user);
        if (message.equals("success")){
            return new DResultMsg(DResultMsg.SUCCESS);
        }else {
            return new DResultMsg(DResultMsg.ERROR,message);
        }
    }

    //
    @PostMapping("/user/{username}/completeUserInfo")
    public DResultMsg completeUserInfo(MultipartFile file, @PathVariable(name = "username") String username,@RequestParam(name = "jsonStr") String jsonStr){
        DResultMsg result = null;
        System.out.println("HELLO completeUserInfo 被执行："+username);
        //获取到传递的参数
        Map params= JSON.parseObject(jsonStr);
        String fileName = fileUpload(file,USER_HEADING_ROOT_PATH,username);
        //String headImage = (String) params.get("headImage");
        if (fileName == null || fileName.length() == 0 || fileName.equals("error")){
            result = new DResultMsg(DResultMsg.ERROR,"上传错误");
        }else {
            User user = new User();
            user.setUsername(username);
            user.setImagePath(fileName);
            user.setName((String)params.get("name"));
            user.setAge(Integer.parseInt((String)params.get("age")));
            user.setCity((String)params.get("city"));
            String message = userService.completeUserInfo(user);
            if (message.equals("success"))
                result = new DResultMsg(DResultMsg.SUCCESS,fileName,"success");
            else
                result = new DResultMsg(DResultMsg.ERROR,"error");
        }
        return result;
    }
    //生成6位随机数字
    public String generateSaltNum(){
        Random random=new Random(System.currentTimeMillis());
        String saltNum= String.valueOf((int) (random.nextDouble() * (1000000 - 100000 + 1) + 100000));
        return saltNum;
    }

    @PostMapping("/message/imageUpload")
    public DResultMsg imageMessageUpload(MultipartFile file, @RequestParam(name = "jsonStr") String jsonStr){
        DResultMsg result = null;
        Map params= JSON.parseObject(jsonStr);
        System.out.println("上传MessageImage方法被调用---");
        //生成文件名
        String senderId = String.valueOf(params.get("senderId"));
        String receiverId = String.valueOf(params.get("receiverId"));
        Date date = new Date(System.currentTimeMillis());
        DateFormat format = new SimpleDateFormat("yyyymmddHHMMSS");
        String time = format.format(date);
        String saltNum = generateSaltNum();
        String newFileName = senderId+receiverId+time+saltNum;
        //保存文件
        String fileName = fileUpload(file,MESSAGE_PICTURE_ROOT_PATH,newFileName);
        if (fileName.equals("error")){
            result = new DResultMsg(DResultMsg.ERROR,"发送文件失败");
        }else {
            //判断一下图片文件长宽类型
            //String type=checkFileSizeType(imageRootPath,fileName.replace("/images/",""));
            HashMap resultData=new HashMap<String,String>();
            resultData.put("fileName",fileName);
            //resultData.put("fileSizeType",type);
            result = new DResultMsg(DResultMsg.SUCCESS,resultData,"success");
        }
        return result;
    }

    @PostMapping("/user/{username}/updateHeadImage")
    public DResultMsg updateHeadImage(MultipartFile file, @PathVariable(name = "username") String username){
        DResultMsg result = null;
        System.out.println("更新头像方法被调用---");
        String fileName = fileUpload(file,USER_HEADING_ROOT_PATH,username);
        if (fileName == null || fileName.length() == 0 || fileName.equals("error")){
            result = new DResultMsg(DResultMsg.ERROR,"上传错误");
        }else {
            User user = new User();
            user.setUsername(username);
            user.setImagePath(fileName);
            String message = userService.updateHeadImage(user);
            if (message.equals("success"))
                result = new DResultMsg(DResultMsg.SUCCESS,fileName,"success");
            else
                result = new DResultMsg(DResultMsg.ERROR,"error");
        }
        return result;
    }
    public String fileUpload(MultipartFile file,String fileDirPath,String fileName){
        //获取上传文件原始文件名
        String originName = file.getOriginalFilename();
        //截取原始文件名后缀
        String suffixName = originName.substring(originName.lastIndexOf("."));
        //文件命名规则（id+suffixName）：UserHeading+username.jpg
        String newFileName = fileName+suffixName;

        File dirFile = new File(imageRootPath,fileDirPath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //文件存储
        File targetFile = null;
        if (isLinux.equals("true")){
            //设置图片存储路径
            targetFile = new File(dirFile, newFileName);
        }else{
            targetFile = new File(newFileName);
        }
        System.out.println(targetFile);
        try {
            file.transferTo(targetFile);
            //返回访问的url：http://+ip+:+port/fileDirPath/newFileName
            return fileDirPath + newFileName;
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
    }
    //通过创建临时文件对图片文件的长宽进行判断
    public String checkFileSizeType(String filePath,String fileName){
        File realFile = new File(filePath+fileName);
        //W表示宽图片，L表示长图片，F表示放图片，这里宽和正方形都按宽图片处理
        String type="W";
        try {
            //转为Image文件
            BufferedImage bufferedImage =ImageIO.read(realFile);
            Integer width = bufferedImage.getWidth();
            Integer height = bufferedImage.getHeight();
            //
            if (width<height){
                type="H";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return type;
    }
    @PostMapping("/user/{username}/updateUserInfo")
    public DResultMsg updateUserInfo(@PathVariable(name = "username") String username,@RequestParam(name = "jsonStr") String jsonStr){
        DResultMsg result = null;
        Map params= JSON.parseObject(jsonStr);
        System.out.println("更新用户信息方法被调用---");
        User user= new User();
        user.setUsername(username);
        user.setName((String)params.get("name"));
        user.setAge(Integer.parseInt((String)params.get("age")));
        user.setCity((String)params.get("city"));
        String message = userService.updateUserInfo(user);
        if (message.equals("success"))
            result = new DResultMsg(DResultMsg.SUCCESS,"success");
        else
            result = new DResultMsg(DResultMsg.ERROR,"error");
        return result;
    }

    //登录
    @PostMapping(value = "/user/login")
    public DResultMsg login(@RequestParam(name = "jsonStr") String jsonStr){
        Map params= JSON.parseObject(jsonStr);
        String message = userService.login((String) params.get("username"),(String) params.get("password"));
        if (message.equals("success")){
            return new DResultMsg(DResultMsg.SUCCESS);
        }else {
            return new DResultMsg(DResultMsg.ERROR,message);
        }
    }

    //首次登录，参数username在路径变量中
    @GetMapping(value = "/user/firstLogin/{username}")
    public DResultMsg firstLogin(@PathVariable("username") String username){
        //获取用户
        User user = userService.getUserByUsername(username);
        //获取好友列表
        ArrayList<User> friendList = new ArrayList<User>();
        //先获取Friend对象，通过Friend对象获取User对象
        //返回的是所有的好友
        ArrayList<Friend> friendItems = friendService.getFriendsByUser(user);
        if (friendItems != null || friendItems.size()>0){
            for (Friend item: friendItems){
                User friend = null;
                if (user.getId() != item.getFriendId())
                    friend = userService.getUserById(item.getFriendId());
                else
                    friend = userService.getUserById(item.getOwnerId());
                friendList.add(friend);
            }
        }
        Map resultMap=new HashMap();
        resultMap.put("owner",user);
        resultMap.put("friends",friendList);
        //返回的是已经是好友关系的好友
        return new DResultMsg(DResultMsg.SUCCESS,resultMap,"success");
    }

    @GetMapping(value ="/user/getUnReadMsg/{username}")
    public DResultMsg getUnReadMsg(@PathVariable("username") String username){
        //获取用户
        User user = userService.getUserByUsername(username);
        //获取未读消息列表
        ArrayList<Message> unReadMessageFormDB = messageService.getUnReadMessage(user.getId());
        if (unReadMessageFormDB != null){
            return new DResultMsg(DResultMsg.SUCCESS,unReadMessageFormDB,"success");
        }
        return new DResultMsg(DResultMsg.ERROR,"error");
    }

    //获取新好友请求列表
    @GetMapping(value ="/user/getNewFriendRequests/{username}")
    public DResultMsg getNewFriends(@PathVariable("username") String username){
        //获取用户
        User user = userService.getUserByUsername(username);
        //获取新的好友请求,返回非好友的集合
        ArrayList<Friend> newFriends = friendService.getNewFriendRequestByUser(user);
        ArrayList<User> resultFriends = new ArrayList<>();
        if (newFriends == null){
            return new DResultMsg(DResultMsg.ERROR,"error");
        }
        for (Friend friend : newFriends){
            User newFriend = userService.getUserById(friend.getFriendId());
            resultFriends.add(newFriend);
        }
        //返回非好友的User集合
        return new DResultMsg(DResultMsg.SUCCESS,resultFriends,"success");
    }

    @GetMapping(value ="/user/searchUser/{username}")
    public DResultMsg searchUser(@PathVariable("username") String username){
        //获取用户
        User user = userService.getUserByUsername(username);
        if (user == null){
            return new DResultMsg(DResultMsg.ERROR,"error");
        }
        return new DResultMsg(DResultMsg.SUCCESS,user,"success");
    }

    @PostMapping(value = "/user/sendFriendRequest")
    public DResultMsg sendFriendRequest(@RequestParam(name = "jsonStr") String jsonStr){
        Map params = JSON.parseObject(jsonStr);
        int friendId = (int)params.get("friendId");
        int userId = (int)params.get("ownerId");
        String message = friendService.sendFriendRequest(userId,friendId);
        if (message.equals("success")){
            return new DResultMsg(DResultMsg.SUCCESS);
        }
        return new DResultMsg(DResultMsg.ERROR,message);
    }

    @PostMapping(value = "/user/acceptFriendRequest")
    public DResultMsg acceptFriendRequest(@RequestParam(name = "jsonStr") String jsonStr){
        Map params = JSON.parseObject(jsonStr);
        int friendId = (int)params.get("friendId");
        int ownerId = (int)params.get("ownerId");
        //同意添加对方位好友后，返回一个对方的User对象
        User newFriend = friendService.accept(ownerId,friendId);
        if (newFriend == null){
            return new DResultMsg(DResultMsg.ERROR,"好友添加错误");
        }
        return new DResultMsg(DResultMsg.SUCCESS,newFriend,"success");
    }
    //拒绝好友
    @PostMapping(value = "/user/rejectFriendRequest")
    public DResultMsg rejectFriendRequest(@RequestParam(name = "jsonStr") String jsonStr){
        Map params = JSON.parseObject(jsonStr);
        int friendId = (int)params.get("friendId");
        int userId = (int)params.get("ownerId");
        String message = friendService.reject(userId,friendId);
        if (message.equals("success")){
            return new DResultMsg(DResultMsg.SUCCESS);
        }
        return new DResultMsg(DResultMsg.ERROR,message);
    }

    @PostMapping(value = "/user/deleteFriendRequest")
    public DResultMsg deleteFriendRequest(@RequestParam(name = "jsonStr") String jsonStr){
        Map params= JSON.parseObject(jsonStr);
        int friendId = (int)params.get("friendId");
        int userId = (int)params.get("ownerId");
        String message = friendService.delete(userId,friendId);
        if (message.equals("success")){
            return new DResultMsg(DResultMsg.SUCCESS);
        }
        return new DResultMsg(DResultMsg.ERROR,message);
    }

    //获取新好友
    @GetMapping(value ="/user/getNewFriends/{username}")
    public DResultMsg getNewFriend(@PathVariable("username") String username){
        User user = userService.getUserByUsername(username);
        ArrayList<User> newFriends = friendService.getNewFriends(user.getId());
        if (newFriends == null){
            return new DResultMsg(DResultMsg.ERROR,"error");
        }
        //返回新朋友的User列表
        return new DResultMsg(DResultMsg.SUCCESS,newFriends,"success");
    }

    //客户端WebsocketClient
    @GetMapping(value ="/user/getNewFriendById/{ownerId}/{friendId}")
    public DResultMsg getNewFriendByNetId(@PathVariable("friendId") String friendId,@PathVariable("ownerId") String ownerId){
        int friendId2 = Integer.parseInt(friendId);
        int ownerId2 = Integer.parseInt(ownerId);
        User user = userService.getUserById(friendId2);
        if (user == null){
            return new DResultMsg(DResultMsg.ERROR,"error");
        }
        friendService.changeNewFriendStatus(friendId2,ownerId2);
        //返回该好友的信息
        return new DResultMsg(DResultMsg.SUCCESS,user,"success");
    }

    @PostMapping(value = "/user/checkFriend")
    public DResultMsg checkFriend(@RequestParam(name = "jsonStr") String jsonStr){
        Map params= JSON.parseObject(jsonStr);
        int friendId = (int)params.get("friendId");
        int userId = (int)params.get("ownerId");
        String message = friendService.checkIsFriend(userId,friendId);
        if (message.equals("success")){
            return new DResultMsg(DResultMsg.SUCCESS);
        }
        return new DResultMsg(DResultMsg.ERROR,message);
    }
}
